#!/usr/bin/env bash
set -euo pipefail

# -------- Config (you can tweak) --------
DATA_SPLITS="data/ThyroidPACS"
DOMAINS_JSON="$DATA_SPLITS/domain_names.json"
MODEL="vit_base_patch16.tv_in1k"
DATASET="ThyroidPACS"
GPU="${GPU:-0}"         # allow override: GPU=1 bash train_expert_all.sh
SEED="${SEED:-42}"      # fixed seed for reproducibility; change or unset if you want randomness
PYTHON="${PYTHON:-python}"
TAG_PREFIX="${TAG_PREFIX:-__thyroid_expert}"  # optional tag if you later want to use --manual-tag
# ----------------------------------------

# Make sure we import local packages
export PYTHONPATH="$(pwd):${PYTHONPATH:-}"

# Try to read first 20 domain names (indices 0..19) from domain_names.json using jq
HOSPITALS=()
if command -v jq >/dev/null 2>&1; then
  # to_entries -> sort by numeric key -> take slice [0:20] -> pull .value
  mapfile -t HOSPITALS < <(jq -r 'to_entries | sort_by(.key|tonumber) | .[0:20] | .[].value' "$DOMAINS_JSON")
else
  echo "[warn] jq not found; falling back to hardcoded list 0..19."
  # Fallback hardcoded names (indices 0..19) — based on your domain_names.json
  HOSPITALS=(
    "上海十院" "上海市一" "华西门诊" "四川省人民" "困难样本"
    "广州市一" "徐州市中心" "无锡市人民" "武汉协和" "沈阳医科大"
    "米诺娃" "胜利油田" "遂宁中心" "颐和" "成都中科"
    "郑大附一" "华西医院" "遵义美年" "华西-赵婉君" "华西-马步云"
  )
fi

echo "=== Will train experts for ${#HOSPITALS[@]} hospitals (indices 0..19) ==="
echo "GPU=$GPU  MODEL=$MODEL  DATASET=$DATASET  SEED=$SEED"
echo

# Sequentially run each hospital; one finishes before the next starts
idx=0
for H in "${HOSPITALS[@]}"; do
  idx=$((idx+1))
  ts=$(date "+%F %T")
  echo "[$ts] ($idx/${#HOSPITALS[@]}) Starting expert training for: ${H}"
  echo "Cmd: $PYTHON train_expert.py --dataset $DATASET --domain \"$H\" --gpu $GPU --model $MODEL --seed $SEED"
  echo "--------------------------------------------------------------------------------"

  # Run training (tqdm 会在前台显示；若用 nohup，会被重定向到日志文件)
  $PYTHON train_expert.py \
    --dataset "$DATASET" \
    --domain "$H" \
    --gpu "$GPU" \
    --model "$MODEL" \
    --seed "$SEED"

  ts_end=$(date "+%F %T")
  echo "[$ts_end] Finished: ${H}"
  echo
  # 可选：短暂停顿，避免日志挤在一起（按需开启）
  # sleep 2
done

echo "=== All expert trainings done. ==="
